<?php

namespace Muyuxuanpay\threePay\src\hk\merchant;

use Muyuxuanpay\http\Http;

trait MerchantTrait
{
    public function getSign(array $data,$int=1)
    {
        if(isset($data['sign'])){
            unset($data['sign']);
        }
        $data = array_filter($data, function ($value) {
            return $value!='';
        });
//        if($int==2){
//            echo "<pre>";
//            print_r($data);
//            exit;
//        }
        if(!empty($data)){
            $str = [];
            ksort($data);
            foreach ($data as $key => $value){
                if($value!=''){
                    if(is_array($value)){
                        $str[] = $key . '=' .$this->getStr($value);
                    }else{
                        $str[] = $key . '=' . strval($value);
                    }
                }
            }
            $str = implode('&', $str);
            $str .= $this->config['accesskey'];
            return strtoupper(md5($str));
        }else{
            $str = '';
            $str .= $this->config['accesskey'];
            return strtoupper(md5($str));
        }
    }
    protected function getStr($value)
    {
        ksort($value);
        $str = [];
        foreach ($value as $key => $val){
            if($val!=""&&is_array($val)){
                $str[] = $key . '=' .  $this->getStr($val);
            }else{
                $str[] = $key . '=' . strval($val);
            }
        }
        return implode('&', $str);
    }
    public function post(string $url, array $data=[])
    {
        $filePath = __DIR__.'/../../../../../test.log';
        file_put_contents($filePath,json_encode($data,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
        $res = Http::sendJson($url,$data);
        if(empty($res)){
            throw new \Exception('请求失败');
        }
        if(is_string($res)){
            $res = json_decode($res,true);
        }
        if(isset($res['sign'])){
            $sign = $this->getSign($res,2);
            if($sign != $res['sign']){
                throw new \Exception('签名错误');
            }
        }
        return $res;
    }
}